package applet.utils;

 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

 


public class ABoxGen{

//	public void init(){
//		try {
//            SwingUtilities.invokeAndWait(new Runnable() {
//                public void run() {
//                	//showStatus("Applet started to create sample KB.");
////                	System.err.println("Getting paramters started.");
////                	writeToKBFile(50, 20, 3);
//                }
//            });
//        } catch (Exception e) {
//            System.err.println("Failed to generate the sample KB.");
//        }
//
//	}
//	private static int nCA=0;
//	private static int nRA=0;
//	private static int nAx=5;
//	private static int nIns=0;
//	
//	private static void clear(){
//		nCA=0;
//		nRA=0;
//		nAx=5;
//		nIns=0;
//	}
	//generate ns students, even: ph_d, odd:Ms, np Profs: 
	//age, gender
	public static String generateStudent(int ns, int np, int ms){
		String st = "";
		List<String> students = new LinkedList<String>();
		List<String> profs = new LinkedList<String>();
		Random cutRd = new Random();
		int genderdiv = cutRd.nextInt(ns+1);
		Random ageRd = new Random();
		String rage = " (role age) ";
		String rsupervised = " (role supervisedBy) ";
		String rgender = " (role gender) ";
		String rname = " (role name) ";
		//loop guards
		String formatstring = "ID%1$08d";
		for(int i = 1; i<=ns; i++){
			String stud = String.format(formatstring, i);
			String cate = i%2 == 0? "PhD_Student" : "MS_Student";
			String gender = i<genderdiv? "male" : "female";
			String age = Integer.toString(ageRd.nextInt(12)+20);
			st += "(concept-assertion "+stud+
					" (and "+cate+" (= "+rage+age+") (= "+rgender+gender+") "+
					" (= "+rname+ "student_"+i+")" +
						")"+
					")\n";
			students.add(stud);
		}
		st += "\n";
		for(int i = ns+1; i <= np+ns; i++){
			String prof = String.format(formatstring, i);
			String cate = "Prof";
			String gender = i%2 == 0? "male" : "female";
			String age = Integer.toString(ageRd.nextInt(35)+30);
			st += "(concept-assertion "+prof+
					" (and "+cate+" (= "+rage+age+") (= "+rgender+gender+") "+
					" (= "+rname+ "prof_"+(i)+")" +
						")"+
					")\n";
			profs.add(prof);
		}
		st += "\n#######Role Assertions#######\n";
		java.util.Collections.shuffle(students);
		java.util.Collections.shuffle(profs);
		//every student will be supervised by someone
		Random psel = new Random();
		int size = profs.size();
		int count = 0;
		for(String stud : students){
			String prof = profs.get(psel.nextInt(size));
			st += "(role-assertion "+stud+" "+prof + rsupervised +")\n";
			if(ms != 0 && (count++ % ms == 0)){
				int ir = psel.nextInt(size);
				String prof2 = profs.get(ir);
				if(prof2.compareToIgnoreCase(prof) == 0){
					prof2 = profs.get((ir+1)%size);
				}
				st += "(role-assertion "+stud+" "+ prof2 + rsupervised +")\n";
			}
		}
		return st;
		//System.err.println(st);
	}
	
	public static String writeToKBFile(int nS, int nP, int every){
		String ret =
			"############ KB Statistics #############\n"+
			"#### Number of Instances: "+(nS+nP)+" \n" +
			"#### Number of Axioms: "+5+" \n" +
			"#### Number of Concept Assertions: "+(nS+nP)+" \n" +
			"#### Number of Role Assertions: "+(every==0? nS: java.lang.Math.round(nS+java.lang.Math.ceil(nS/every)))+" \n" +
			"############ ------------- #############\n\n"+
		"######\n" +
		"# TBox\n" + 
		"######\n\n" + "(implies Student Person)\n# Grad requires >= 1 years of studies\n" +
		"(implies Grad_Student  (and (forall (role supervisedBy) Prof) Student (not (< (role yearsOfStudy) 01)) ))\n" +
		"# PhD requires >= 4 years of studies\n" + 
		"(implies PhD_Student (and (not MS_Student) Grad_Student (not (< (role yearsOfStudy) 04)) ) )\n" + 
		"(implies MS_Student (and (not PhD_Student) Grad_Student))\n"
		+ "(implies Prof (and Person (not Student)))\n\n" + 
		"######\n" + 
		"# ABox\n" + 
		"# Students: even number: PhD, odd number: Master; age (20~32) and gender are randomly assigned.\n"
		+ "# Professors: even number: male, odd number: female; age is randomly assigned (30~65).\n" + 
		"# Supervision relation: n-to-n relation, a portion of students have 2 supervisors.\n"+
		"######\n\n";
		ret += generateStudent(nS, nP, every);
		//String locurl = this.getCodeBase().
		String fname = "sample_"+nS+"_"+nP+"_"+every+".kbox";
		//showStatus("File generated successfully:"+fname);
		writeOutKBFile("/Projects/WebDeployment/kb/"+fname, ret);	
		return fname;
	}
	
	public static void main(String[] args) {
//		int[] studs = { 50, 100, 300, 500};
//		int[] profs = { 20, 50, 100, 300};
//		int[] mps = {0, 5, 10, 20};
//		for(int i =0; i<studs.length; i++){
//			for(int j=0; j<profs.length; j++){
//				for(int k=0; k<mps.length; k++){
//					System.out.println(writeToKBFile(studs[i], profs[j], mps[k]));
//				}
//			}
//		}
		writeToKBFile(4, 2, 0);
	}
	
	private static void writeOutKBFile(String f, String s){
		FileWriter fstream = null;
	    BufferedWriter out = null;
	    File file = new File(f);
		try {
			fstream = new FileWriter(file, false);
	        out = new BufferedWriter(fstream);
			out.write(s);
			out.newLine();
		} catch (IOException e) {
			System.err.println("KB file cannot be generated.");
			e.printStackTrace();
		}finally{
			try {
				fstream.flush();
				//fstream.close();
				out.flush();
				out.close();
			} catch (IOException e) {
				//System.out.println("file loc: "+f);
				e.printStackTrace();
			}
		}

	}
	
}
